package com.mx;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@RestController
public class Demo02Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo02Application.class, args);
    }

    @Bean
    public Redisson getRedisson() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.50.2:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    Redisson redisson;
    @RequestMapping("/")
    public String hello(){
        // 之所以谁不同的lockKey是因为  如果超时  很可能会出现整个锁失效的情况
        String lockKey="mx_lock";
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(lockKey, "true",5, TimeUnit.SECONDS);
        if(!isLock){
            //System.out.println("没拿到锁");
            return "";
        }
        try {
            int count = Integer.parseInt(redisTemplate.opsForValue().get("count"));
            if(count>0){
                int cur=count-1;
                redisTemplate.opsForValue().set("count",String.valueOf(cur));
                System.out.println( "购买成功"+cur);
            }else {
                //System.out.println("购买失败");
            }
        }catch (Exception e){
            return "error";
        }finally {
            redisTemplate.delete(lockKey);
        }

        return "";
    }
    @RequestMapping("/1")
    public String hello1() {
        String lockKey = "mx_lock";
        String uuid = UUID.randomUUID().toString();
        RLock lock = redisson.getLock(lockKey);

        try {
            lock.lock();
            int count = Integer.parseInt(redisTemplate.opsForValue().get("count"));
            if (count > 0) {
                int cur = count - 1;
                redisTemplate.opsForValue().set("count", String.valueOf(cur));
                System.out.println("购买成功" + cur);
            } else {
                //System.out.println("购买失败");
            }
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
        return "";
    }
}
